<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha256-wiz7ZSCn/btzhjKDQBms9Hx4sSeUYsDrTLg7roPstac=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.css" integrity="sha256-6cQIC71/iBIYXFK+0RHAvwmjwWzkWd+r7v/BX3/vZDc=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/green/pace-theme-minimal.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"sumumm.github.io","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.19.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":true,"height":300},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="本文主要是进程——线程的创建与回收的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:type" content="article">
<meta property="og:title" content="LV05-02-线程-02-线程的创建与回收">
<meta property="og:url" content="https://sumumm.github.io/post/4e20d76.html">
<meta property="og:site_name" content="苏木">
<meta property="og:description" content="本文主要是进程——线程的创建与回收的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-02-%E7%BA%BF%E7%A8%8B-02-%E7%BA%BF%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%9B%9E%E6%94%B6/img/image-20220527154120122.png">
<meta property="article:published_time" content="2023-07-02T13:52:01.000Z">
<meta property="article:modified_time" content="2025-06-13T16:25:56.993Z">
<meta property="article:author" content="苏木">
<meta property="article:tag" content="LV05-操作系统">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-02-%E7%BA%BF%E7%A8%8B-02-%E7%BA%BF%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%9B%9E%E6%94%B6/img/image-20220527154120122.png">


<link rel="canonical" href="https://sumumm.github.io/post/4e20d76.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://sumumm.github.io/post/4e20d76.html","path":"post/4e20d76.html","title":"LV05-02-线程-02-线程的创建与回收"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>LV05-02-线程-02-线程的创建与回收 | 苏木</title>
  








    <script src="/js/browser_tools_disable.js"></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<!-- hexo injector head_end start --><link rel="stylesheet" href="https://unpkg.com/hexo-next-tags-plus@latest/lib/tag_plus.css" media="defer" onload="this.media='all'"><!-- hexo injector head_end end --></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">苏木</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">我的学习之路</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>苏木的家</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类页<span class="badge">42</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档页<span class="badge">673</span></a></li><li class="menu-item menu-item-flink"><a href="/flink/" rel="section"><i class="fa fa-link fa-fw"></i>友人帐</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于我</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E7%BA%BF%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA"><span class="nav-text">一、线程的创建</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%A6%82%E4%BD%95%E5%88%9B%E5%BB%BA%E7%BA%BF%E7%A8%8B%EF%BC%9F"><span class="nav-text">1. 如何创建线程？</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-pthread-create"><span class="nav-text">1.1 pthread_create() </span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">1.1.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">1.1.2 使用实例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%8F%82%E6%95%B0%E7%9A%84%E4%BC%A0%E9%80%92"><span class="nav-text">2. 参数的传递</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-%E5%9C%B0%E5%9D%80%E4%BC%A0%E9%80%92"><span class="nav-text">2.1 地址传递</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-1-%E5%BA%94%E8%AF%A5%E6%80%8E%E4%B9%88%E5%86%99%EF%BC%9F"><span class="nav-text">2.1.1 应该怎么写？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B1"><span class="nav-text">2.1.2 使用实例1</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B2"><span class="nav-text">2.1.2 使用实例2</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-3-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B3"><span class="nav-text">2.1.3 使用实例3</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-%E5%80%BC%E4%BC%A0%E9%80%92"><span class="nav-text">2.2 值传递</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-1-%E5%BA%94%E8%AF%A5%E6%80%8E%E4%B9%88%E5%86%99%EF%BC%9F"><span class="nav-text">2.2.1 应该怎么写？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-1-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B1"><span class="nav-text">2.2.1 使用实例1</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B2"><span class="nav-text">2.2.2 使用实例2</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E5%8F%AF%E4%BB%A5%E5%88%9B%E5%BB%BA%E5%A4%9A%E5%B0%91%E7%BA%BF%E7%A8%8B%EF%BC%9F"><span class="nav-text">3. 可以创建多少线程？</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-%E5%BD%B1%E5%93%8D%E5%9B%A0%E7%B4%A0%EF%BC%9F"><span class="nav-text">3.1 影响因素？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-32-%E4%BD%8D%E7%B3%BB%E7%BB%9F"><span class="nav-text">3.2 32 位系统</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-64-%E4%BD%8D%E7%B3%BB%E7%BB%9F"><span class="nav-text">3.3 64 位系统</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E7%BA%BF%E7%A8%8B%E7%BB%88%E6%AD%A2"><span class="nav-text">二、线程终止</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E7%BB%88%E6%AD%A2%E7%BA%BF%E7%A8%8B%E7%9A%84%E6%96%B9%E5%BC%8F"><span class="nav-text">1. 终止线程的方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E7%BB%88%E6%AD%A2%E5%87%BD%E6%95%B0"><span class="nav-text">2. 终止函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-pthread-exit"><span class="nav-text">2.1 pthread_exit() </span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">2.1.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">2.1.2 使用实例</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E7%BA%BF%E7%A8%8B%E5%9B%9E%E6%94%B6"><span class="nav-text">三、线程回收</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%83%B5%E5%B0%B8%E7%BA%BF%E7%A8%8B"><span class="nav-text">1. 僵尸线程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%9B%9E%E6%94%B6%E5%87%BD%E6%95%B0"><span class="nav-text">2. 回收函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-pthread-join"><span class="nav-text">2.1 pthread_join() </span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E-1"><span class="nav-text">2.1.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B-1"><span class="nav-text">2.1.2 使用实例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E5%86%85%E5%AD%98%E6%BC%94%E7%A4%BA"><span class="nav-text">3. 内存演示</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E4%B8%8E%E8%BF%9B%E7%A8%8B%E5%9B%9E%E6%94%B6%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="nav-text">4. 与进程回收的区别</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="苏木"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">苏木</p>
  <div class="site-description" itemprop="description">莫道桑榆晚，为霞尚满天</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">673</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">42</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">43</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/sumumm" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;sumumm" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://sumumm.github.io/post/4e20d76.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="苏木">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苏木">
      <meta itemprop="description" content="莫道桑榆晚，为霞尚满天">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="LV05-02-线程-02-线程的创建与回收 | 苏木">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          LV05-02-线程-02-线程的创建与回收
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-07-02 21:52:01" itemprop="dateCreated datePublished" datetime="2023-07-02T21:52:01+08:00">2023-07-02</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">嵌入式开发</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/" itemprop="url" rel="index"><span itemprop="name">01HQ课程体系</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/" itemprop="url" rel="index"><span itemprop="name">LV05-操作系统</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>8.1k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>29 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>本文主要是进程——线程的创建与回收的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。</p>
<span id="more"></span>

<!-- Photo: https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-02-%E7%BA%BF%E7%A8%8B-02-%E7%BA%BF%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%9B%9E%E6%94%B6/img/ -->

<details class="folding-tag" blue><summary> 点击查看使用工具及版本 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center" width=150px>Windows</td>        <td align="left">windows11</td>    </tr>    <tr>        <td align="center">Ubuntu</td>        <td align="left">Ubuntu16.04的64位版本</td>      </tr>    <tr>        <td align="center">VMware® Workstation 16 Pro</td>        <td align="left">16.2.3 build-19376536</td>      </tr>    <tr>        <td align="center">SecureCRT</td>        <td align="left">Version 8.7.2 (x64 build 2214)   -   正式版-2020年5月14日</td>      </tr>    <tr>        <td align="center">开发板</td>        <td align="left">正点原子 i.MX6ULL Linux阿尔法开发板</td>      </tr>    <tr>        <td align="center">uboot</td>        <td align="left">NXP官方提供的uboot，NXP提供的版本为uboot-imx-rel_imx_4.1.15_2.1.0_ga(使用的uboot版本为U-Boot 2016.03)</td>      </tr>    <tr>        <td align="center">linux内核</td>        <td align="left">linux-4.15(NXP官方提供)</td>      </tr>    <tr>        <td align="center">STM32开发板</td>        <td align="left">正点原子战舰V3(STM32F103ZET6)</td>      </tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看本文参考资料 </summary>
              <div class='content'>
              <table>    <tr><td align="center">参考方向  </td><td align="center">参考原文</td></tr>    <tr><td align="left">---</td><td align="left"><a href="" target="_blank">--- <i class="fa fa-external-link-alt"></i> </a></td></tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看相关文件下载 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center" width=150>---</td>        <td align="left"><a href="" target="_blank">---<i class="fa fa-external-link-alt"></i> </a></td>      </tr></table>
              </div>
            </details>

<h1 id="一、线程的创建"><a href="#一、线程的创建" class="headerlink" title="一、线程的创建"></a><font size=3>一、线程的创建</font></h1><h2 id="1-如何创建线程？"><a href="#1-如何创建线程？" class="headerlink" title="1. 如何创建线程？"></a><font size=3>1. 如何创建线程？</font></h2><h3 id="1-1-pthread-create"><a href="#1-1-pthread-create" class="headerlink" title="1.1 pthread_create() "></a><font size=3>1.1 pthread_create() </font></h3><h4 id="1-1-1-函数说明"><a href="#1-1-1-函数说明" class="headerlink" title="1.1.1 函数说明"></a><font size=3>1.1.1 函数说明</font></h4><p>在 linux 下可以使用 man pthread_create 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Compile and link with -pthread. */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_create</span><span class="params">(<span class="type">pthread_t</span> *thread, <span class="type">const</span> <span class="type">pthread_attr_t</span> *attr, <span class="type">void</span> *(*start_routine) (<span class="type">void</span> *), <span class="type">void</span> *arg)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数创建一个新的线程，创建出来的新线程被称为主线程的子线程。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>thread ： pthread_t * 类型，当 pthread_create() 成功返回时，新创建的线程的线程 ID 会保存在参数 thread 所指向的内存中，后续的线程相关函数会使用该标识来引用此线程。</li>
<li>attr ： pthread_attr_t * 类型，指向 pthread_attr_t 类型的缓冲区， pthread_attr_t 数据类型定义了线程的各种属性。如果将参数 attr 设置为 NULL ，那么表示将线程的所有属性设置为默认值，以此创建新线程。</li>
<li>start_routine ：参数 start_routine 是一个函数指针，指向一个函数，新创建的线程从 start_routine() 函数开始运行，该函数返回值类型为 void * ，并且该函数的参数只有一个 void * ，其实这个参数就是 pthread_create() 函数的第四个参数 arg 。如果需要向 start_routine() 传递的参数有一个以上，那么需要把这些参数放到一个结构体中，然后把这个结构体对象的地址作为 arg 参数传入。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看该形参的详细解释 </summary>
              <div class='content'>
              <p>这个参数是什么，到底指向什么？</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> *(*start_routine) (<span class="type">void</span> *)</span><br></pre></td></tr></table></figure><p>（1）*start_routine 表示这是一个指针变量，指针变量名为 start_routine ;</p><p>（2）后边的 (void *) 表示这个指针变量可以指向带有一个 void * 类型形参的函数；</p><p>（3）前边的 void * 表示这个指针变量可以指向返回值为 void * 类型的函数；</p><p>总的说起来就是，这句话定义了一个可以指向带一个 void * 参数且返回值为 void * 类型的函数的指针变量 start_routine 。</p>
              </div>
            </details>

<ul>
<li>arg ：传递给 start_routine() 函数的参数。一般情况下，需要将 arg 指向一个全局或堆变量，意思就是说在线程的生命周期中，该 arg 指向的对象必须存在，否则如果线程中访问了该对象将会出现错误。当然也可将参数 arg 设置为 NULL ，表示不需要传入参数给 start_routine() 函数。</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回 0 ；失败时将返回一个错误号，并且参数 thread 指向的内容是不确定的。</p>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">int</span> ret;</span><br><span class="line"><span class="type">pthread_t</span> tid; <span class="comment">/*  使用printf()打印数据的时候，格式应该使用lu。 */</span></span><br><span class="line">ret = pthread_create(&amp;tid, <span class="literal">NULL</span>, (<span class="type">void</span> *)testThread, <span class="literal">NULL</span>);<span class="comment">/* testThread 要有定义*/</span></span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong></p>
<p>（1） pthread_create() 在调用失败时通常会返回错误码，它并不像其它库函数或系统调用一样设置 errno ，每个线程都提供了全局变量 errno 的副本，这只是为了与使用 errno 到的函数进行兼容，在线程中，从函数中返回错误码更为清晰整洁，不需要依赖那些随着函数执行不断变化的全局变量，这样可以把错误的范围限制在引起出错的函数中。</p>
<p>（2）线程创建成功，新线程就会加入到系统调度队列中，获取到 CPU 之后就会立马从 start_routine() 函数开始运行该线程的任务；调用 pthread_create() 函数后，通常我们无法确定系统接着会调度哪一个线程来使用 CPU 资源，先调度主线程还是新创建的线程呢（而在多核 CPU 或多 CPU 系统中，多核线程可能会在不同的核心上同时执行）？如果程序对执行顺序有强制要求，那么就<strong>必须采用一些同步技术来实现</strong>。</p>
<h4 id="1-1-2-使用实例"><a href="#1-1-2-使用实例" class="headerlink" title="1.1.2 使用实例"></a><font size=3>1.1.2 使用实例</font></h4><details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <p>【说明】主线程休眠了 1 秒钟，原因在于，如果主线程不进行休眠，它就可能会立马退出，这样可能会导致新创建的线程还没有机会运行，整个进程就结束了。</p><figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span><span class="comment">/* pthread_create */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span> <span class="comment">/* sleep */</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> *<span class="title function_">testThread</span><span class="params">(<span class="type">void</span> *arg)</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> ret;</span><br><span class="line">	<span class="type">pthread_t</span> tid;</span><br><span class="line">	<span class="comment">/* 1. 创建一个线程 */</span></span><br><span class="line">	ret = pthread_create(&amp;tid, <span class="literal">NULL</span>, (<span class="type">void</span> *)testThread, <span class="literal">NULL</span>);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;This is main thread,ret=%d,tid=%lu,pthread_self=%lu,pid=%d\n&quot;</span>, ret, tid, pthread_self(), getpid());  </span><br><span class="line">	</span><br><span class="line">	sleep(<span class="number">3</span>);<span class="comment">/* 这里停留一下，创建的线程才有时间运行 */</span></span><br><span class="line">	</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> *<span class="title function_">testThread</span><span class="params">(<span class="type">void</span> *arg)</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;This is child thread,pthread_self=%lu,pid=%d\n&quot;</span>,pthread_self(), getpid());  </span><br><span class="line">	</span><br><span class="line">	<span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out</span><br></pre></td></tr></table></figure><p>要是没啥意外的话，应该会报以下 error ：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">/usr/bin/ld: /tmp/ccE9ZZGr.o: in function  main&#x27;:</span><br><span class="line">test.c:(.text+0x3b): undefined reference to  pthread_create&#x27;</span><br><span class="line">collect2: error: ld returned 1 exit status</span><br></pre></td></tr></table></figure><p>我们明明包含了相关头文件啊？前边 man 查看手册的时候，有这么一句话 Compile and link with -pthread. ，这便是问题所在，我们编译程序的时候需要加上 prhread 链接库就可以啦（ -l 与 pthread 之间有无空格都可以）：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall -l pthread # 生成可执行文件 a.out </span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">This is main thread,ret=0,tid=139924118435392,pthread_self=139924121261888,pid=4119</span><br><span class="line">This is child thread,pthread_self=139924118435392,pid=4119</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h2 id="2-参数的传递"><a href="#2-参数的传递" class="headerlink" title="2. 参数的传递"></a><font size=3>2. 参数的传递</font></h2><h3 id="2-1-地址传递"><a href="#2-1-地址传递" class="headerlink" title="2.1 地址传递"></a><font size=3>2.1 地址传递</font></h3><h4 id="2-1-1-应该怎么写？"><a href="#2-1-1-应该怎么写？" class="headerlink" title="2.1.1 应该怎么写？"></a><font size=3>2.1.1 应该怎么写？</font></h4><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 新创建的线程开始函数 */</span></span><br><span class="line"><span class="type">int</span> *<span class="title function_">testThread</span><span class="params">(<span class="type">void</span> *arg)</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 主函数中创建新线程的语句 */</span></span><br><span class="line">pthread_create(&amp;tid, <span class="literal">NULL</span>, (<span class="type">void</span> *)testThread, <span class="literal">NULL</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数原型 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_create</span><span class="params">(<span class="type">pthread_t</span> *thread, <span class="type">const</span> <span class="type">pthread_attr_t</span> *attr, <span class="type">void</span> *(*start_routine) (<span class="type">void</span> *), <span class="type">void</span> *arg)</span>;</span><br></pre></td></tr></table></figure>

<p>在上边的 pthread_create 函数中，我们知道最后的 arg 参数是可以传入 start_routine 指向的函数的，他们参数的类型都是 void * ，既然是指针，我们可以定义一个变量，传入地址即可。若是定义的变量为整型，那么定义变量&rarr;传入参数&rarr;使用参数的格式解读如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 定义变量格式 */</span></span><br><span class="line"><span class="type">int</span> arg = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 参数传入格式，强制转化为指向(void *)类型的地址 */</span></span><br><span class="line">(<span class="type">void</span> *)&amp;arg </span><br><span class="line">    </span><br><span class="line"><span class="comment">/* 参数使用格式，强制转化为指向(int *)类型的地址，然后再取地址内的数据 */</span></span><br><span class="line">*(<span class="type">int</span> *)arg </span><br></pre></td></tr></table></figure>

<h4 id="2-1-2-使用实例1"><a href="#2-1-2-使用实例1" class="headerlink" title="2.1.2 使用实例1"></a><font size=3>2.1.2 使用实例1</font></h4><details class="folding-tag" blue><summary> 点击查看实例1 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span><span class="comment">/* pthread_create pthread_exit pthread_self */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span> <span class="comment">/* sleep */</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *<span class="title function_">testThreadParam1</span><span class="params">(<span class="type">void</span> *arg)</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> ret;</span><br><span class="line">	<span class="type">pthread_t</span> tid;</span><br><span class="line">	<span class="type">int</span> arg = <span class="number">5</span>; <span class="comment">/* 要传入的参数 */</span></span><br><span class="line">	<span class="comment">/* 1. 创建一个线程 */</span></span><br><span class="line">	ret = pthread_create(&amp;tid, <span class="literal">NULL</span>, testThreadParam1, (<span class="type">void</span> *)&amp;arg);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;This is main thread,ret=%d,tid=%lu\n&quot;</span>, ret, tid);  </span><br><span class="line">	</span><br><span class="line">	sleep(<span class="number">1</span>);<span class="comment">/* 这里停留一下，创建的线程才有时间运行 */</span></span><br><span class="line">	</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *<span class="title function_">testThreadParam1</span><span class="params">(<span class="type">void</span> *arg)</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;This is a new thread test! pid=%d,tid=%lu\n&quot;</span>, getpid(), pthread_self());</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;input arg=%d\n&quot;</span>, *(<span class="type">int</span> *)arg);</span><br><span class="line">	<span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall -l pthread # 生成可执行文件 a.out </span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">This is main thread,ret=0,tid=139903662814784</span><br><span class="line">This is a new thread test! pid=4472,tid=139903662814784</span><br><span class="line">input arg=5</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p>通过上边的实例，我们会发现，变量做了正确的强制类型转换，正常的按地址传递，没有警告，参数的传递也没有问题。</p>
<h4 id="2-1-2-使用实例2"><a href="#2-1-2-使用实例2" class="headerlink" title="2.1.2 使用实例2"></a><font size=3>2.1.2 使用实例2</font></h4><p>我们再来试一下创建 5 个子线程，并将参数传递进去，我们来看一看会发生什么现象。</p>
<details class="folding-tag" blue><summary> 点击查看实例2 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span><span class="comment">/* pthread_create pthread_exit pthread_self */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span> <span class="comment">/* sleep */</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *<span class="title function_">testThreadParam</span><span class="params">(<span class="type">void</span> *arg)</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> ret;</span><br><span class="line">	<span class="type">pthread_t</span> tid[<span class="number">5</span>];</span><br><span class="line">	<span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">/* 1. 创建一个线程 */</span></span><br><span class="line">		ret = pthread_create(&amp;tid[i], <span class="literal">NULL</span>, testThreadParam, (<span class="type">void</span> *)&amp;i);</span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;This is %d thread create,ret=%d,tid=%lu\n&quot;</span>, i, ret, tid[i]);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	sleep(<span class="number">5</span>);<span class="comment">/* 这里停留一下，创建的线程才有时间运行 */</span></span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="type">void</span> *<span class="title function_">testThreadParam</span><span class="params">(<span class="type">void</span> *arg)</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;This is %d new thread.tid=%lu\n&quot;</span>, *(<span class="type">int</span> *)arg, pthread_self());</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall -l pthread # 生成可执行文件 a.out </span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">This is 0 thread create,ret=0,tid=140107547932224</span><br><span class="line">This is 1 new thread.tid=140107547932224</span><br><span class="line">This is 1 thread create,ret=0,tid=140107539539520</span><br><span class="line">This is 2 thread create,ret=0,tid=140107531146816</span><br><span class="line">This is 3 new thread.tid=140107531146816</span><br><span class="line">This is 3 new thread.tid=140107539539520</span><br><span class="line">This is 3 thread create,ret=0,tid=140107522754112</span><br><span class="line">This is 4 new thread.tid=140107522754112</span><br><span class="line">This is 4 thread create,ret=0,tid=140107514361408</span><br><span class="line">This is 5 new thread.tid=140107514361408</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p>我们会发现，传入的到线程执行函数的参数与线程并不对应，这是为什么？原因就在于，线程创建后执行是不确定的，由于我们传入的是地址，创建出来的几个线程传入的参数都是这个地址中的数据，而线程创建后，可能并没有执行，就又创建了下一个线程，这就导致参数传递出现了问题。</p>
<h4 id="2-1-3-使用实例3"><a href="#2-1-3-使用实例3" class="headerlink" title="2.1.3 使用实例3"></a><font size=3>2.1.3 使用实例3</font></h4><p>由实例 2 的问题，我们可以想一下，线程执行顺序的不确定导致了问题的出现，那我创建后休眠一下，给线程运行的时间，让线程从不同的时间开始运行，是不是不就好了呢？，我们可以尝试一下：</p>
<details class="folding-tag" blue><summary> 点击查看实例3 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span><span class="comment">/* pthread_create pthread_exit pthread_self */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span> <span class="comment">/* sleep */</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *<span class="title function_">testThreadParam</span><span class="params">(<span class="type">void</span> *arg)</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> ret;</span><br><span class="line">	<span class="type">pthread_t</span> tid[<span class="number">5</span>];</span><br><span class="line">	<span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">/* 1. 创建一个线程 */</span></span><br><span class="line">		ret = pthread_create(&amp;tid[i], <span class="literal">NULL</span>, testThreadParam, (<span class="type">void</span> *)&amp;i);</span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;This is %d thread create,ret=%d,tid=%lu\n&quot;</span>, i, ret, tid[i]);</span><br><span class="line">        sleep(<span class="number">1</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	sleep(<span class="number">1</span>);<span class="comment">/* 这里停留一下，创建的线程才有时间运行 */</span></span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="type">void</span> *<span class="title function_">testThreadParam</span><span class="params">(<span class="type">void</span> *arg)</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;This is %d new thread.tid=%lu\n&quot;</span>, *(<span class="type">int</span> *)arg, pthread_self());</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall -l pthread # 生成可执行文件 a.out </span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">This is 0 thread create,ret=0,tid=139647833339456</span><br><span class="line">This is 0 new thread.tid=139647833339456</span><br><span class="line">This is 1 thread create,ret=0,tid=139647824946752</span><br><span class="line">This is 1 new thread.tid=139647824946752</span><br><span class="line">This is 2 thread create,ret=0,tid=139647816554048</span><br><span class="line">This is 2 new thread.tid=139647816554048</span><br><span class="line">This is 3 thread create,ret=0,tid=139647808161344</span><br><span class="line">This is 3 new thread.tid=139647808161344</span><br><span class="line">This is 4 thread create,ret=0,tid=139647799768640</span><br><span class="line">This is 4 new thread.tid=139647799768640</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p>可以发现，这样得出的参数是正确的，但是我们等待程序完成也等待了很久，无疑是很浪费时间的。</p>
<h3 id="2-2-值传递"><a href="#2-2-值传递" class="headerlink" title="2.2 值传递"></a><font size=3>2.2 值传递</font></h3><h4 id="2-2-1-应该怎么写？"><a href="#2-2-1-应该怎么写？" class="headerlink" title="2.2.1 应该怎么写？"></a><font size=3>2.2.1 应该怎么写？</font></h4><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 新创建的线程开始函数 */</span></span><br><span class="line"><span class="type">int</span> *<span class="title function_">testThread</span><span class="params">(<span class="type">void</span> *arg)</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 主函数中创建新线程的语句 */</span></span><br><span class="line">pthread_create(&amp;tid, <span class="literal">NULL</span>, (<span class="type">void</span> *)testThread, <span class="literal">NULL</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数原型 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_create</span><span class="params">(<span class="type">pthread_t</span> *thread, <span class="type">const</span> <span class="type">pthread_attr_t</span> *attr, <span class="type">void</span> *(*start_routine) (<span class="type">void</span> *), <span class="type">void</span> *arg)</span>;</span><br></pre></td></tr></table></figure>

<p>在上边的 pthread_create 函数中，我们知道传入的是一个地址，可是一想，地址不也是数值嘛？难道就不能把一个数字强行当做一个地址，然后直接访问这个转换过的地址，不也可以吗。那就来尝试一下吧。若是定义的变量为整型，那么定义变量&rarr;传入参数&rarr;使用参数的格式解读如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 定义变量格式 */</span></span><br><span class="line"><span class="type">int</span> arg = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 参数传入格式，强行将 1 当做一个void类型的地址进行参数传入 */</span></span><br><span class="line">(<span class="type">void</span> *)arg </span><br><span class="line">    </span><br><span class="line"><span class="comment">/* 参数使用格式，由于传参的时候转化为了void类型，所以使用的时候需要强制转化回来 */</span></span><br><span class="line">(<span class="type">int</span>)arg </span><br></pre></td></tr></table></figure>

<p><strong>【注意】</strong>这样做会导致指针长度不匹配问题，有可能会导致数据出错，这就需要我们自己来把握了。上边的变量定义为 int 类型，而在 64 位平台下，指针是占据 8 字节，长度长于 int 类型，这样是不会有问题的，但是如果使用了比指针还要长的数据长度时，就要注意这个问题了，防止数据丢失。</p>
<h4 id="2-2-1-使用实例1"><a href="#2-2-1-使用实例1" class="headerlink" title="2.2.1 使用实例1"></a><font size=3>2.2.1 使用实例1</font></h4><details class="folding-tag" blue><summary> 点击查看实例1 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span><span class="comment">/* pthread_create pthread_exit pthread_self */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span> <span class="comment">/* sleep */</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *<span class="title function_">testThreadParam1</span><span class="params">(<span class="type">void</span> *arg)</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> ret;</span><br><span class="line">	<span class="type">pthread_t</span> tid;</span><br><span class="line">	<span class="type">int</span> arg = <span class="number">5</span>; <span class="comment">/* 要传入的参数 */</span></span><br><span class="line">	<span class="comment">/* 1. 创建一个线程 */</span></span><br><span class="line">	ret = pthread_create(&amp;tid, <span class="literal">NULL</span>, testThreadParam1, (<span class="type">void</span> *)arg);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;This is main thread,ret=%d,tid=%lu\n&quot;</span>, ret, tid);  </span><br><span class="line">	</span><br><span class="line">	sleep(<span class="number">1</span>);<span class="comment">/* 这里停留一下，创建的线程才有时间运行 */</span></span><br><span class="line">	</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *<span class="title function_">testThreadParam1</span><span class="params">(<span class="type">void</span> *arg)</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;This is a new thread test! pid=%d,tid=%lu\n&quot;</span>, getpid(), pthread_self());</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;input arg=%d\n&quot;</span>, (<span class="type">int</span>)arg);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;after pthread exit\n&quot;</span>);</span><br><span class="line">	pthread_exit(<span class="literal">NULL</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall -l pthread # 生成可执行文件 a.out </span><br></pre></td></tr></table></figure><p>没啥大问题的话，应该会出现下边的警告提示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">test.c: In function ‘main’:</span><br><span class="line">test.c:13:53: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]</span><br><span class="line">   13 | thread_create(&amp;tid, NULL, testThreadParam1, (void *)arg);</span><br><span class="line">      |                                             ^</span><br><span class="line"></span><br><span class="line">test.c: In function ‘testThreadParam1’:</span><br><span class="line">test.c:24:27: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]</span><br><span class="line">   24 |  printf(&quot;input arg=%d\n&quot;, (int)arg);</span><br><span class="line">      | </span><br></pre></td></tr></table></figure><p>原因是什么呢？上边其实已经解释过了，这是强制转化导致的数据所占字节数量不一致导致的，我们自己把握好保证数据不出错就可以啦。然后执行可执行程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">This is main thread,ret=0,tid=139766219667008</span><br><span class="line">This is a new thread test! pid=4816,tid=139766219667008</span><br><span class="line">input arg=5</span><br><span class="line">after pthread exit</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p>通过上边的例子，我们会发现，除了一个警告外，参数的传递没有问题。</p>
<h4 id="2-2-2-使用实例2"><a href="#2-2-2-使用实例2" class="headerlink" title="2.2.2 使用实例2"></a><font size=3>2.2.2 使用实例2</font></h4><p>那么我们再来试一下创建 5 个子线程，并将参数传递进去，我们来看一看会不会产生地址传递的问题。</p>
<details class="folding-tag" blue><summary> 点击查看实例2 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span><span class="comment">/* pthread_create pthread_exit pthread_self */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span> <span class="comment">/* sleep */</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *<span class="title function_">testThreadParam</span><span class="params">(<span class="type">void</span> *arg)</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> ret;</span><br><span class="line">	<span class="type">pthread_t</span> tid[<span class="number">5</span>];</span><br><span class="line">	<span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">/* 1. 创建一个线程 */</span></span><br><span class="line">		ret = pthread_create(&amp;tid[i], <span class="literal">NULL</span>, testThreadParam, (<span class="type">void</span> *)i);</span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;This is %d thread create,ret=%d,tid=%lu\n&quot;</span>, i, ret, tid[i]);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	sleep(<span class="number">1</span>);<span class="comment">/* 这里停留一下，创建的线程才有时间运行 */</span></span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="type">void</span> *<span class="title function_">testThreadParam</span><span class="params">(<span class="type">void</span> *arg)</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;This is %d new thread.tid=%lu\n&quot;</span>, (<span class="type">int</span>)arg, pthread_self());</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall -l pthread # 生成可执行文件 a.out 依然会有警告，我们自己把握好就可以</span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">This is 0 thread create,ret=0,tid=139813761599040</span><br><span class="line">This is 1 thread create,ret=0,tid=139813753206336</span><br><span class="line">This is 0 new thread.tid=139813761599040</span><br><span class="line">This is 2 thread create,ret=0,tid=139813744813632</span><br><span class="line">This is 3 thread create,ret=0,tid=139813736420928</span><br><span class="line">This is 4 thread create,ret=0,tid=139813728028224</span><br><span class="line">This is 2 new thread.tid=139813744813632</span><br><span class="line">This is 1 new thread.tid=139813753206336</span><br><span class="line">This is 3 new thread.tid=139813736420928</span><br><span class="line">This is 4 new thread.tid=139813728028224</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p>我们会发现，传入的到线程执行函数的参数与线程是对应的，值是没有问题的，并且我们并没有控制线程的执行顺序。这在后边可能会有很大的用处。</p>
<h2 id="3-可以创建多少线程？"><a href="#3-可以创建多少线程？" class="headerlink" title="3. 可以创建多少线程？"></a><font size=3>3. 可以创建多少线程？</font></h2><h3 id="3-1-影响因素？"><a href="#3-1-影响因素？" class="headerlink" title="3.1 影响因素？"></a><font size=3>3.1 影响因素？</font></h3><p>我们可以通过进程来创建线程，那么，一个进程最多可以创建多少线程呢？在  Linux  操作系统中，虚拟地址空间的内部又被分为内核空间和用户空间两部分，不同位数的系统，地址空间的范围也不同。</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-02-%E7%BA%BF%E7%A8%8B-02-%E7%BA%BF%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%9B%9E%E6%94%B6/img/image-20220527154120122.png" alt="image-20220527154120122" style="zoom: 40%;" />

<p>进程创建线程时，线程的最大数量与以下两个部分有关：</p>
<ul>
<li><strong>进程的虚拟内存空间上限</strong>，因为创建一个线程，操作系统需要为其分配一个栈空间，如果线程数量越多，所需的栈空间就要越大，那么虚拟内存就会占用的越多。</li>
<li><strong>系统参数限制</strong>，虽然  Linux  并没有内核参数来控制单个进程创建的最大线程个数，但是有系统级别的参数来控制整个系统的最大线程个数。</li>
</ul>
<p>我们先来看一看创建一个线程，系统默认分配的虚拟内存大小吧，我们可以在终端输入以下命令：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ulimit -a</span><br></pre></td></tr></table></figure>

<div class="tabs" id="tabname0"><ul class="nav-tabs"><li class="tab active"><a href="#tabname0-1">32位</a></li><li class="tab"><a href="#tabname0-2">64位</a></li></ul><div class="tab-content"><div class="tab-pane active" id="tabname0-1"><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">core file size          (blocks, -c) unlimited</span><br><span class="line">data seg size           (kbytes, -d) unlimited</span><br><span class="line">scheduling priority             (-e) 0</span><br><span class="line">file size               (blocks, -f) unlimited</span><br><span class="line">pending signals                 (-i) 7862</span><br><span class="line">max locked memory       (kbytes, -l) 64</span><br><span class="line">max memory size         (kbytes, -m) unlimited</span><br><span class="line">open files                      (-n) 1024</span><br><span class="line">pipe size            (512 bytes, -p) 8</span><br><span class="line">POSIX message queues     (bytes, -q) 819200</span><br><span class="line">real-time priority              (-r) 0</span><br><span class="line">stack size              (kbytes, -s) 8192</span><br><span class="line">cpu time               (seconds, -t) unlimited</span><br><span class="line">max user processes              (-u) 7862</span><br><span class="line">virtual memory          (kbytes, -v) unlimited</span><br><span class="line">file locks                      (-x) unlimited</span><br></pre></td></tr></table></figure></div><div class="tab-pane" id="tabname0-2"><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">real-time non-blocking time  (microseconds, -R) unlimited</span><br><span class="line">core file size              (blocks, -c) 0</span><br><span class="line">data seg size               (kbytes, -d) unlimited</span><br><span class="line">scheduling priority                 (-e) 0</span><br><span class="line">file size                   (blocks, -f) unlimited</span><br><span class="line">pending signals                     (-i) 15308</span><br><span class="line">max locked memory           (kbytes, -l) 498501</span><br><span class="line">max memory size             (kbytes, -m) unlimited</span><br><span class="line">open files                          (-n) 1024</span><br><span class="line">pipe size                (512 bytes, -p) 8</span><br><span class="line">POSIX message queues         (bytes, -q) 819200</span><br><span class="line">real-time priority                  (-r) 0</span><br><span class="line">stack size                  (kbytes, -s) 8192</span><br><span class="line">cpu time                   (seconds, -t) unlimited</span><br><span class="line">max user processes                  (-u) 15308</span><br><span class="line">virtual memory              (kbytes, -v) unlimited</span><br><span class="line">file locks                          (-x) unlimited</span><br></pre></td></tr></table></figure></div></div></div>

<h3 id="3-2-32-位系统"><a href="#3-2-32-位系统" class="headerlink" title="3.2 32 位系统"></a><font size=3>3.2 32 位系统</font></h3><p>在 32 位系统下，按照每个线程 10MB 的大小创建线程，共有 3GB 可用虚拟存，这样一共大概是 300 个线程左右。我们可以写一个测试程序，测试一下 32 位系统下究竟可以创建多少线程。</p>
<details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span><span class="comment">/* pthread_create pthread_exit pthread_cancel pthread_self */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span> <span class="comment">/* sleep */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;string.h&gt;</span> <span class="comment">/* strerror */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;errno.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *<span class="title function_">testThread</span><span class="params">(<span class="type">void</span> *arg)</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">while</span>(<span class="number">1</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		sleep(<span class="number">1</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> (<span class="type">void</span> *)<span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> err = <span class="number">0</span>;</span><br><span class="line">	<span class="type">int</span> count = <span class="number">0</span>;</span><br><span class="line">	<span class="type">pthread_t</span> tid;</span><br><span class="line">	<span class="keyword">while</span>(err == <span class="number">0</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		err = pthread_create(&amp;tid, <span class="literal">NULL</span>, testThread, <span class="literal">NULL</span>);</span><br><span class="line">		count++;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;create thread error: %s\n&quot;</span>, strerror(errno));</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;Maxmum number of thread within a process is %d\n&quot;</span>, count);</span><br><span class="line">	getchar();<span class="comment">/* 进程不结束，便于查看线程和进程情况 */</span></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall -l pthread # 生成可执行文件 a.out </span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">create thread error: Cannot allocate memory</span><br><span class="line">Maxmum number of thread within a process is 384</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p>【结论】 32  位系统，用户态的虚拟空间只有  3G ，如果创建线程时分配的栈空间是  10M ，那么一个进程最多只能创建  300  个左右的线程。</p>
<h3 id="3-3-64-位系统"><a href="#3-3-64-位系统" class="headerlink" title="3.3 64 位系统"></a><font size=3>3.3 64 位系统</font></h3><p>我使用的测试系统是 Ubuntu21.04 的 64 位版本，在虚拟机中运行，分配了 2 个单核 CPU ，分配的内存为 4GB 。 64  位系统意味着用户空间的虚拟内存最大值是  128TB ，这个数值是很大的，如果按创建一个线程需占用  10M  栈空间的情况来算，那么理论上可以创建  128TB&#x2F;10MB  个线程，也就是  1000 多万个线程。</p>
<p>但是肯定创建不了那么多线程，除了虚拟内存的限制，还有系统的限制。比如下面这三个内核参数的大小，都会影响创建线程的上限：</p>
<ul>
<li>&#x2F;proc&#x2F;sys&#x2F;kernel&#x2F;threads-max ，表示系统支持的最大线程数，默认值是  14553 ；</li>
<li>&#x2F;proc&#x2F;sys&#x2F;kernel&#x2F;pid_max ，表示系统全局的  PID  号数值的限制，每一个进程或线程都有  ID ， ID  的值超过这个数，进程或线程就会创建失败，默认值是  32768 ；</li>
<li>proc&#x2F;sys&#x2F;vm&#x2F;max_map_count ，表示限制一个进程可以拥有的 VMA (虚拟内存区域)的数量，具体什么意思呢，我也不是很清楚啦，反正如果它的值很小，也会导致创建线程失败，默认值是  65530 。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span><span class="comment">/* pthread_create pthread_exit pthread_cancel pthread_self */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span> <span class="comment">/* sleep */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;string.h&gt;</span> <span class="comment">/* strerror */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;errno.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *<span class="title function_">testThread</span><span class="params">(<span class="type">void</span> *arg)</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">while</span>(<span class="number">1</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		sleep(<span class="number">1</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> (<span class="type">void</span> *)<span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> err = <span class="number">0</span>;</span><br><span class="line">	<span class="type">int</span> count = <span class="number">0</span>;</span><br><span class="line">	<span class="type">pthread_t</span> tid;</span><br><span class="line">	<span class="keyword">while</span>(err == <span class="number">0</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		err = pthread_create(&amp;tid, <span class="literal">NULL</span>, testThread, <span class="literal">NULL</span>);</span><br><span class="line">		count++;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;create thread error: %s\n&quot;</span>, strerror(errno));</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;Maxmum number of thread within a process is %d\n&quot;</span>, count);</span><br><span class="line">	getchar();<span class="comment">/* 进程不结束，便于查看线程和进程情况 */</span></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall -l pthread # 生成可执行文件 a.out </span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">create thread error: Resource temporarily unavailable</span><br><span class="line">Maxmum number of thread within a process is 9859</span><br></pre></td></tr></table></figure><p>可以发现，最多创建了 9859 个，并且，此时重新开一个终端的话，是无法开启的。</p>
              </div>
            </details>

<p>【结论】 64  位系统，用户态的虚拟空间大到有  128T ，理论上不会受虚拟内存大小的限制，而会受系统的参数或性能限制。</p>
<h1 id="二、线程终止"><a href="#二、线程终止" class="headerlink" title="二、线程终止"></a><font size=3>二、线程终止</font></h1><h2 id="1-终止线程的方式"><a href="#1-终止线程的方式" class="headerlink" title="1. 终止线程的方式"></a><font size=3>1. 终止线程的方式</font></h2><p>终止线程一般有如下方式：</p>
<p>（1）线程的 start 函数执行 return 语句并返回指定值，返回值就是线程的退出码； return 的返回值可以通过 pthread_join() 来获取的。</p>
<p>（2）线程调用 pthread_exit() 函数；</p>
<p>（3）调用 pthread_cancel() 取消线程</p>
<p><strong>【注意】</strong>如果进程中的任意线程调用 exit() 、 _exit() 或者 _Exit() ，那么将会导致整个进程终止。</p>
<h2 id="2-终止函数"><a href="#2-终止函数" class="headerlink" title="2. 终止函数"></a><font size=3>2. 终止函数</font></h2><h3 id="2-1-pthread-exit"><a href="#2-1-pthread-exit" class="headerlink" title="2.1 pthread_exit() "></a><font size=3>2.1 pthread_exit() </font></h3><h4 id="2-1-1-函数说明"><a href="#2-1-1-函数说明" class="headerlink" title="2.1.1 函数说明"></a><font size=3>2.1.1 函数说明</font></h4><p>在 linux 下可以使用 man pthread_create 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Compile and link with -pthread. */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="type">void</span> <span class="title function_">pthread_exit</span><span class="params">(<span class="type">void</span> *retval)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数将终止调用它的线程。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>retval ： void * 类型，指定了线程的返回值（并非是函数的返回值）、也就是线程的退出码，这个退出码可以是数值，也可以是字符串。并且该退出码可由另一个线程通过调用 pthread_join() 来获取；同理，如果线程是在 start 函数中执行 return 语句终止，那么 return 的返回值也是可以通过 pthread_join() 来获取的。</li>
</ul>
<p><strong>【返回值】</strong> none </p>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line">pthread_exit((<span class="type">void</span> *)<span class="number">0</span>);</span><br><span class="line">pthread_exit(<span class="literal">NULL</span>);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong></p>
<p>（1）若需要设置退出码，且退出码为数值时，要注意做数据类型转换。</p>
<p>（2）调用 pthread_exit() 相当于在线程的 start 函数中执行 return 语句，不同之处在于，可在线程 start 函数所调用的任意函数中调用 pthread_exit() 来终止线程。如果主线程调用了 pthread_exit() ，那么主线程也会终止，但其它线程依然正常运行，直到进程中的所有线程终止才会使得进程终止。</p>
<h4 id="2-1-2-使用实例"><a href="#2-1-2-使用实例" class="headerlink" title="2.1.2 使用实例"></a><font size=3>2.1.2 使用实例</font></h4><details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span><span class="comment">/* pthread_create pthread_exit*/</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span> <span class="comment">/* sleep */</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *<span class="title function_">testThreadExit</span><span class="params">(<span class="type">void</span> *arg)</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> ret;</span><br><span class="line">	<span class="type">pthread_t</span> tid;</span><br><span class="line">	<span class="comment">/* 1. 创建一个线程 */</span></span><br><span class="line">	ret = pthread_create(&amp;tid, <span class="literal">NULL</span>, testThreadExit, <span class="literal">NULL</span>);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;This is main thread,ret=%d,tid=%lu\n&quot;</span>, ret, tid); </span><br><span class="line">	sleep(<span class="number">1</span>);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;main pthread exit!\n&quot;</span>);</span><br><span class="line">	pthread_exit(<span class="literal">NULL</span>);</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* void  pthread_exit(void *retval); */</span></span><br><span class="line"><span class="type">void</span> * <span class="title function_">testThreadExit</span><span class="params">(<span class="type">void</span> *arg)</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;This is a new thread test!\n&quot;</span>);</span><br><span class="line">	sleep(<span class="number">2</span>);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;new pthread exit!\n&quot;</span>);</span><br><span class="line">	pthread_exit(<span class="literal">NULL</span>);</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall -l pthread # 生成可执行文件 a.out </span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">This is main thread,ret=0,tid=140561027761728</span><br><span class="line">This is a new thread test!</span><br><span class="line">main pthread exit!</span><br><span class="line">new pthread exit!</span><br></pre></td></tr></table></figure><p>新线程中调用 sleep() 休眠，保证主线程先调用 pthread_exit() 终止，休眠结束之后新线程也调用 pthread_exit() 终止，根据打印结果，主线程调用 pthread_exit() 终止之后，整个进程并没有结束，而新线程还在继续运行。</p>
              </div>
            </details>

<h1 id="三、线程回收"><a href="#三、线程回收" class="headerlink" title="三、线程回收"></a><font size=3>三、线程回收</font></h1><h2 id="1-僵尸线程"><a href="#1-僵尸线程" class="headerlink" title="1. 僵尸线程"></a><font size=3>1. 僵尸线程</font></h2><p>若线程并未分离（ detached，啥意思？后边会学习到 ），则必须使用 pthread_join() 来等待线程终止，回收线程资源，这是因为如果线程终止后，其它线程没有调用 pthread_join() 函数来回收该线程，那么该线程将变成<strong>僵尸线程</strong>，与僵尸进程的概念相类似。同样，僵尸线程除了浪费系统资源外，若僵尸线程积累过多，那么会导致应用程序无法创建新的线程。</p>
<p>不过如果进程中存在着僵尸线程并未得到回收，当进程终止之后，进程会被其父进程回收，所以僵尸线程同样也会被回收。</p>
<h2 id="2-回收函数"><a href="#2-回收函数" class="headerlink" title="2. 回收函数"></a><font size=3>2. 回收函数</font></h2><h3 id="2-1-pthread-join"><a href="#2-1-pthread-join" class="headerlink" title="2.1 pthread_join() "></a><font size=3>2.1 pthread_join() </font></h3><h4 id="2-1-1-函数说明-1"><a href="#2-1-1-函数说明-1" class="headerlink" title="2.1.1 函数说明"></a><font size=3>2.1.1 函数说明</font></h4><p>在 linux 下可以使用 man pthread_join 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Compile and link with -pthread. */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_join</span><span class="params">(<span class="type">pthread_t</span> thread, <span class="type">void</span> **retval)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数将阻塞等待线程的终止，并获取线程的退出码，回收线程资源。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>thread ： pthread_t 类型， pthread_join() 等待指定线程的终止，通过参数 thread （线程 ID ）指定需要等待的线程。</li>
<li>retval ：如果参数 retval 不为 NULL ，则 pthread_join() 将目标线程的退出状态（即目标线程通过 pthread_exit() 退出时指定的返回值或者在线程 start 函数中执行 return 语句对应的返回值）复制到 *retval 所指向的内存区域；如果目标线程被 pthread_cancel() 取消，则将 PTHREAD_CANCELED 放在 *retval 中。如果对目标线程的终止状态不感兴趣，则可将参数 retval 设置为 NULL 。</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回 0 ，失败时返回错误码。</p>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">void</span> *retv;</span><br><span class="line">pthread_join(tid, *retval);<span class="comment">/* retval打印的时候注意类型的转换 */</span></span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong>调用 pthread_join() 函数将会以阻塞的形式等待指定的线程终止，如果该线程已经终止，则 pthread_join() 立刻返回。如果多个线程同时尝试调用 pthread_join() 等待指定线程的终止，那么结果将是不确定的。</p>
<h4 id="2-1-2-使用实例-1"><a href="#2-1-2-使用实例-1" class="headerlink" title="2.1.2 使用实例"></a><font size=3>2.1.2 使用实例</font></h4><details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span><span class="comment">/* pthread_create pthread_exit pthread_self pthread_join */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span> <span class="comment">/* sleep */</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *<span class="title function_">threadJoin</span><span class="params">(<span class="type">void</span> *arg)</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> ret;</span><br><span class="line">	<span class="type">pthread_t</span> tid[<span class="number">5</span>];</span><br><span class="line">	<span class="type">void</span> *retv;</span><br><span class="line">	<span class="type">int</span> i;</span><br><span class="line">	<span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">/* 1. 创建一个线程 */</span></span><br><span class="line">		ret = pthread_create(&amp;tid[i], <span class="literal">NULL</span>, threadJoin, (<span class="type">void</span> *)i);</span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;This is [%d] thread create,ret=%d,tid=%lu\n&quot;</span>, i, ret, tid[i]);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">/* 2. 回收线程 */</span></span><br><span class="line">		pthread_join(tid[i],&amp;retv);<span class="comment">/* 以阻塞的形式等待指定的线程终止 */</span></span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;thread[%d] retv=%s\n&quot;</span>, i, (<span class="type">char</span>*)retv);</span><br><span class="line">	&#125;</span><br><span class="line">	sleep(<span class="number">1</span>);<span class="comment">/* 这里停留一下，创建的线程才有时间运行 */</span></span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *<span class="title function_">threadJoin</span><span class="params">(<span class="type">void</span> *arg)</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;This is [%d] thread test! pid=%d,tid=%lu\n&quot;</span>,(<span class="type">int</span>)arg, getpid(), pthread_self());</span><br><span class="line">	sleep(<span class="number">1</span>);</span><br><span class="line">	pthread_exit(<span class="string">&quot;thread return!&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall -l pthread # 生成可执行文件 a.out 依然会有警告，我们自己把握好就可以</span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">This is [0] thread create,ret=0,tid=140469036594752</span><br><span class="line">This is [1] thread create,ret=0,tid=140469028202048</span><br><span class="line">This is [2] thread create,ret=0,tid=140469019809344</span><br><span class="line">This is [3] thread create,ret=0,tid=140469011416640</span><br><span class="line">This is [4] thread create,ret=0,tid=140469003023936</span><br><span class="line">This is [1] thread test! pid=3458,tid=140469028202048</span><br><span class="line">This is [0] thread test! pid=3458,tid=140469036594752</span><br><span class="line">This is [2] thread test! pid=3458,tid=140469019809344</span><br><span class="line">This is [3] thread test! pid=3458,tid=140469011416640</span><br><span class="line">This is [4] thread test! pid=3458,tid=140469003023936</span><br><span class="line">thread[0] retv=thread return!</span><br><span class="line">thread[1] retv=thread return!</span><br><span class="line">thread[2] retv=thread return!</span><br><span class="line">thread[3] retv=thread return!</span><br><span class="line">thread[4] retv=thread return!</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h2 id="3-内存演示"><a href="#3-内存演示" class="headerlink" title="3. 内存演示"></a><font size=3>3. 内存演示</font></h2><p>僵尸进程是可以直接使用 ps 命令看到的，是否真的被回收是很直观的，但是线程不同，是否真的被回收，我们好像是看不到的，不过我们可以通过 top 命令来查看我们进程所占用的内存资源，当结束的线程被回收后，应当是内存资源占用变小，若未回收已结束的线程，则内存资源应当不发生变化才对。</p>
<details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <p>通过宏 pthreadJoin 是否定义来选择是否编译线程回收部分程序，以达到测试的目的。</p><figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span><span class="comment">/* pthread_create pthread_exit pthread_self pthread_join */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span> <span class="comment">/* sleep */</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> pthreadJoin <span class="comment">/* 控制是否开启线程回收 */</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *<span class="title function_">threadJoin</span><span class="params">(<span class="type">void</span> *arg)</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> ret;</span><br><span class="line">	<span class="type">pthread_t</span> tid[<span class="number">5</span>];</span><br><span class="line">	<span class="type">void</span> *retv;</span><br><span class="line">	<span class="type">int</span> i;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;This main:pid=%d\n&quot;</span>, getpid());</span><br><span class="line">	<span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; <span class="number">100</span>; i++)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">/* 1. 创建一个线程 */</span></span><br><span class="line">		ret = pthread_create(&amp;tid[i], <span class="literal">NULL</span>, threadJoin, (<span class="type">void</span> *)i);</span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;This is [%d] thread create,ret=%d,tid=%lu\n&quot;</span>, i, ret, tid[i]);</span><br><span class="line">	&#125;</span><br><span class="line"><span class="meta">#<span class="keyword">ifdef</span> pthreadJoin</span></span><br><span class="line">	<span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; <span class="number">100</span>; i++)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">/* 2. 回收线程 */</span></span><br><span class="line">		pthread_join(tid[i],&amp;retv);<span class="comment">/* 以阻塞的形式等待指定的线程终止 */</span></span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;thread[%d] retv=%s\n&quot;</span>, i, (<span class="type">char</span>*)retv);</span><br><span class="line">	&#125;</span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br><span class="line">	<span class="keyword">while</span>(<span class="number">1</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		sleep(<span class="number">1</span>);<span class="comment">/* 这里停留一下，创建的线程才有时间运行 */</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *<span class="title function_">threadJoin</span><span class="params">(<span class="type">void</span> *arg)</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;This is [%d] thread test! pid=%d,tid=%lu\n&quot;</span>,(<span class="type">int</span>)arg, getpid(), pthread_self());</span><br><span class="line">	sleep(<span class="number">25</span>);</span><br><span class="line">	pthread_exit(<span class="string">&quot;thread return!&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall -l pthread # 生成可执行文件 a.out 依然会有警告，我们自己把握好就可以</span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">This is [0] thread,ret=0,tid=139887072605760</span><br><span class="line">This is [0] thread test! pid=6543,tid=139887072605760</span><br><span class="line">This is [1] thread,ret=0,tid=139887064213056</span><br><span class="line">This is [2] thread,ret=0,tid=139887055820352</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">其他的省略 ...</span></span><br></pre></td></tr></table></figure><p>这里我们只关注 pid 的值即可，因为这是进程的 PID 然后重新开一个终端输入以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">top -p 6543</span><br></pre></td></tr></table></figure><p>然后便会进入动态查看该进程变化情况的界面，显示信息如下：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">top - 16:07:36 up8:  09,1 user, load average: 0.00，0.00,0.00</span><br><span class="line">任务:1 total,0 running, 1 sleeping, 0 stopped, 0 zombie</span><br><span class="line"><span class="meta prompt_">%</span><span class="language-bash">Cpu(s): 0.3 us,0.3 Sy,0.0 ni, 99.3 <span class="built_in">id</span>,0.0 wa,0.0 hi,0.0 si,0.0 st</span></span><br><span class="line">MiB Mem :  3894.5 total, 1620.9 free, 1188.6 used, 1085.1 buff/cache</span><br><span class="line">MiB Swap : 1162.4total,  1162.4 free,    0.0 used. 2410.2 avail Mem</span><br><span class="line"></span><br><span class="line">进程号 USER      PR  NI    VIRT    RES    SHR    %CPU  %MEM     TIME+ COMMAND</span><br><span class="line"> 6874 hk        20   0  101076   1904   1724 S   0.0   0.0   0:00.00 a.out</span><br></pre></td></tr></table></figure><p>然后我们关注 VIRT 一栏的信息即可。其实差别还是特别明显的。</p>
              </div>
            </details>

<h2 id="4-与进程回收的区别"><a href="#4-与进程回收的区别" class="headerlink" title="4. 与进程回收的区别"></a><font size=3>4. 与进程回收的区别</font></h2><p>通过上面的介绍可知， pthread_join() 执行的功能类似于针对进程的 waitpid() 调用，不过二者之间存在一些显著差别：</p>
<p>（1）线程之间关系是对等的。进程中的任意线程均可调用 pthread_join() 函数来等待另一个线程的终止。例如，如果线程 A 创建了线程 B ，线程 B 再创建线程 C ，那么线程 A 可以调用 pthread_join() 等待线程 C 的终止，线程 C 也可以调用 pthread_join() 等待线程 A 的终止；这与进程间层次关系不同，父进程如果使用 fork() 创建了子进程，那么它也是唯一能够对子进程调用 wait() 的进程，线程之间不存在这样的关系。</p>
<p>（）不能以非阻塞的方式调用 pthread_join() 。对于进程，调用 waitpid() 既可以实现阻塞方式等待、也可以实现非阻塞方式等待。</p>

    </div>

    
    
    

    <footer class="post-footer">




    <div>
        
            <div style="text-align:center;color: #ccc;font-size:14px;">
            ----------本文结束
            <i class="fas fa-fan fa-spin" style="color: #FF1493; font-size: 1rem"></i>
            感谢您的阅读----------
            </div>
        
    </div>





  
  <div class="my_post_copyright"> 
    <p><span>文章标题:</span><a href="/post/4e20d76.html">LV05-02-线程-02-线程的创建与回收</a></p>
    <p><span>文章作者:</span><a href="/" title="欢迎访问 《苏木》 的学习笔记">苏木</a></p>
    <p><span>发布时间:</span>2023年07月02日 - 21:52</p>
    <p><span>最后更新:</span>2025年06月14日 - 00:25</p>
    <p><span>原始链接:</span><a href="/post/4e20d76.html" title="LV05-02-线程-02-线程的创建与回收">https://sumumm.github.io/post/4e20d76.html</a></p>
    <p><span>许可协议:</span><i class="fab fa-creative-commons"></i> <a rel="license" href= "https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
  </div>
  


          <div class="post-tags">
              <a href="/tags/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/" rel="tag"><i class="fa fa-tag"></i> LV05-操作系统</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/post/fe0255c0.html" rel="prev" title="LV05-02-线程-03-线程属性">
                  <i class="fa fa-angle-left"></i> LV05-02-线程-03-线程属性
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/post/326a1e35.html" rel="next" title="LV05-02-线程-01-线程的基础知识">
                  LV05-02-线程-01-线程的基础知识 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2017 – 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">苏木</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">3.7m</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">225:26</span>
  </span>
</div>




    <span id="sitetime"></span>
    <script defer language=javascript>
        function siteTime()
        {
            window.setTimeout("siteTime()", 1000);
            var seconds = 1000;
            var minutes = seconds * 60;
            var hours = minutes * 60;
            var days = hours * 24;
            var years = days * 365;
            var today = new Date();
            var todayYear = today.getFullYear();
            var todayMonth = today.getMonth()+1;
            var todayDate = today.getDate();
            var todayHour = today.getHours();
            var todayMinute = today.getMinutes();
            var todaySecond = today.getSeconds();
            /*==================================================
            Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
            year        - 作为date对象的年份，为4位年份值
            month       - 0-11之间的整数，做为date对象的月份
            day         - 1-31之间的整数，做为date对象的天数
            hours       - 0(午夜24点)-23之间的整数，做为date对象的小时数
            minutes     - 0-59之间的整数，做为date对象的分钟数
            seconds     - 0-59之间的整数，做为date对象的秒数
            microseconds - 0-999之间的整数，做为date对象的毫秒数
            ==================================================*/
            var t1 = Date.UTC(2017, 
                              5, 
                              19, 
                              0, 
                              0, 
                              0); //北京时间
            var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
            var diff = t2-t1;
            var diffYears = Math.floor(diff/years);
            var diffDays = Math.floor((diff/days)-diffYears*365);
            var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
            var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
            var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
            document.getElementById("sitetime").innerHTML="已在这里 "+diffYears+" 年 "+diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
        }
        siteTime();
    </script>



    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.umd.js" integrity="sha256-ytMJGN3toR+a84u7g7NuHm91VIR06Q41kMWDr2pq7Zo=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>

  <script src="/js/third-party/pace.js"></script>


  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


 
        <div id="click-show-text"
            data-mobile = false
            data-text = 富强,民主,文明,和谐,自由,平等,公正,法制,爱国,敬业,诚信,友善
            data-fontsize = 15px
            data-random= false>
        </div>
       

      
        <script async src=https://cdn.jsdelivr.net/npm/hexo-next-mouse-effect@latest/click/showText.js></script>
      

      
    




    <script async src="/js/fancybox_param.js"></script>





<!-- APlayer本体 -->



</body>
</html>
